<template>
  <div v-if="showEditor" class="editor-container">
    <div class="title">{{ title }}</div>
    <div style="border: 1px solid #ccc; width: 50vw">
      <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        :mode="mode"
      />
      <Editor
        style="height: 50vh; overflow-y: hidden"
        v-model="valueHtml"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="handleCreated"
      />
    </div>
    <div class="operate">
      <el-button type="warning" @click="handleChangeShow">关闭编辑器</el-button>
      <el-button type="primary" @click="handleModifyText">确认修改内容</el-button>
    </div>
  </div>
</template>

<script setup>
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted, computed, watch } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
const props = defineProps({
  showEditor: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    required: true,
  },
  text: {
    type: String,
    default: "",
  },
});
const emits = defineEmits(["changeShowEditor", "getModifiedText"]);
const mode = "simple"; // 或 'default'
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 内容 HTML
const valueHtml = ref("<p>回显的内容</p>");

// 模拟 ajax 异步获取内容
onMounted(() => {
  setTimeout(() => {
    valueHtml.value = props.text;
  }, 1500);
});

watch(
  () => props.text,
  (newVal, oldVal) => {
    valueHtml.value = newVal;
  },
  { immediate: true, deep: true }
);

const toolbarConfig = {};
const editorConfig = { placeholder: "请输入内容..." };

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};

function handleChangeShow() {
  emits("changeShowEditor", false);
}

function handleModifyText() {
  emits("getModifiedText", valueHtml.value);
}
</script>

<style lang="scss" scoped>
.editor-container {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  background: rgba($color: #000000, $alpha: 0.7);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  .title {
    background: #c6d3e9;
    width: 50vw;
    text-align: center;
    font-size: 1.2vw;
    color: #fff;
    padding: 1vh 0;
    font-weight: 600;
  }
  .operate {
    margin-top: 2vh;
  }
}
</style>
